<template>
  <!-- 保留一个最大的div，因为页面有卡片、有弹层等 -->
  <div>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>文章列表</span>
      </div>
      <!-- 内容区 -->
      <!-- 内容区一：表单搜索区 -->
      <div class="search-box">
        <!-- inline属性，控制表单项，以水平方式排列 -->
        <el-form :inline="true" class="demo-form-inline">
          <el-form-item label="文章分类">
            <el-select placeholder="文章分类" v-model="getData.cate_id">
              <el-option
                v-for="item in cateList"
                :key="item.id"
                :label="item.cate_name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="文章状态">
            <el-select placeholder="文章状态" v-model="getData.state">
              <el-option label="已发布" value="已发布"></el-option>
              <el-option label="草稿" value="草稿"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="query">查询</el-button>
            <el-button type="info" @click="reset">重置</el-button>
          </el-form-item>
        </el-form>
        <el-button type="primary" class="add-btn" @click="dialogVisible = true">添加文章</el-button>
      </div>
      <!-- 内容区二：表格区，展示数据 -->
      <el-table :data="showDatalist" border stripe>
        <el-table-column prop="title" label="标题" width="250px"> </el-table-column>
        <el-table-column prop="cate_name" label="分类" width="250px"> </el-table-column>
        <el-table-column label="时间" width="250px">
          <template v-slot="obj">{{ obj.row.pub_date | time_format }}</template>
        </el-table-column>
        <el-table-column prop="state" label="状态" width="250px"> </el-table-column>
        <el-table-column label="操作"> </el-table-column>
      </el-table>
      <!-- 内容区三：分页区 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="1"
        :page-sizes="[2, 4, 6, 8, 10]"
        :page-size="4"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
    <!-- 文章编辑弹窗 -->
    <el-dialog
      title="添加文章"
      :visible.sync="dialogVisible"
      :before-close="handleClose"
      fullscreen
    >
      <!-- 添加的表单 start -->
      <el-form label-width="80px" :model="addData" :rules="rules" ref="addartlice">
        <!-- 第一行：文章标题 -->
        <el-form-item label="文章标题" prop="title">
          <el-input v-model="addData.title" placeholder="请输入标题"></el-input>
        </el-form-item>
        <!-- 第二行：选择分类 -->
        <el-form-item label="选择分类" prop="cate_id">
          <el-select placeholder="请选择分类" style="width: 100%" v-model="addData.cate_id">
            <el-option
              v-for="item in cateList"
              :key="item.id"
              :label="item.cate_name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <!-- 第三行，文章内容 -->
        <el-form-item label="文章内容">
          <quill-editor v-model="addData.content"></quill-editor>
        </el-form-item>
        <!-- 第四行：文章封面 -->
        <el-form-item label="文章封面">
          <div>
            <img :src="imgUrl" class="cover-img" alt="" v-if="imgUrl" />
            <img src="@/assets/images/cover.jpg" class="cover-img" alt="" v-else />
          </div>
          <input type="file" style="display: none" ref="fileRef" @change="chooseimg($event)" />
          <el-button type="text" icon="el-icon-plus" @click="$refs.fileRef.click()"
            >选择图片</el-button
          >
        </el-form-item>
        <!-- 第五行：文章状态 -->
        <el-form-item>
          <el-button type="primary" @click="publish('已发布')">保存发布</el-button>
          <el-button type="info" @click="publish('草稿')">存为草稿</el-button>
        </el-form-item>
      </el-form>
      <!-- 添加的表单 end -->
    </el-dialog>
  </div>
</template>

<script>
import dayjs from 'dayjs'
import { addArtliceAPI, ArtliceListAPI } from '@/api/artilce'
export default {
  name: 'MyCarlist',
  data() {
    return {
      dialogVisible: false,
      // 添加文章的数据项，用于存储添加表单中的每一项数据
      addData: {
        title: '', // 文章标题
        cate_id: '', // 下拉框的值，取值为分类id（为什么叫做 cate_id，因为接口文档的字段叫cate_id）
        content: '',
        cover_img: '',
        state: ''
      },
      imgUrl: '',
      cateList: [...this.$store.state.cate.cateList],
      // 验证规则对象
      rules: {
        title: [
          { required: true, message: '标题必填', trigger: 'blur' },
          { min: 1, max: 30, message: '标题长度1~30位', trigger: ['change', 'blur'] }
        ],
        cate_id: [
          { required: true, message: '必须选择一个分类', trigger: ['blur', 'change'] },
          {
            pattern: /^[1-9][0-9]*$/,
            message: '分类id必须是大于0的整数',
            trigger: ['blur', 'change']
          }
        ]
      },
      showDatalist: [],
      getData: {
        pagenum: 1,
        pagesize: 4,
        cate_id: '',
        state: ''
      },
      total: 0
    }
  },
  methods: {
    // 关闭添加文章对象框
    handleClose(dorn) {
      this.$confirm('可能会导致文章信息丢失，是否继续?', '提示', {
        type: 'warning'
      })
        .then(() => {
          this.$refs.addartlice.resetFields()
          this.addData.content = ''
          this.addData.cover_img = ''
          this.imgUrl = ''
          dorn()
        })
        .catch(() => {
          this.$message.info('已取消')
        })
    },
    chooseimg(e) {
      if (e.target.files.length > 0) {
        this.addData.cover_img = e.target.files[0]
        this.imgUrl = URL.createObjectURL(e.target.files[0])
      } else {
        this.addData.cover_img = ''
        this.imgUrl = ''
      }
    },
    // 提交发布文章
    publish(s) {
      this.addData.state = s
      this.$refs.addartlice.validate(async valid => {
        if (!valid) return
        if (this.addData.content === '') return this.$message.warning('内容不能为空')
        if (this.addData.cover_img === '') return this.$message.warning('照片不能为空')
        const fd = new FormData()
        for (const key in this.addData) {
          fd.append(key, this.addData[key])
        }
        const { data: res } = await addArtliceAPI(fd)
        if (res.code === 0) {
          this.$message.success(res.message)
          this.dialogVisible = false
          // 清空表单
          this.$refs.addartlice.resetFields()
          this.addData.content = ''
          this.addData.cover_img = ''
          this.imgUrl = ''
          // 重新获取列表数据
        } else {
          this.$message.error(res.message)
        }
      })
    },
    // 获取文章列表信息
    async getShowDatalist() {
      const { data: res } = await ArtliceListAPI(this.getData)
      if (res.code === 0) {
        this.showDatalist = res.data
        this.total = res.total
      }
    },
    // 分页功能
    // 每页多少条
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      this.getData.pagesize = val
      this.getShowDatalist()
    },
    // 当前第几页
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      this.getData.pagenum = val
      this.getShowDatalist()
    },
    reset() {
      this.getData.cate_id = ''
      this.getData.state = ''
    },
    query() {
      this.getShowDatalist()
    }
  },
  created() {
    this.getShowDatalist()
  },
  filters: {
    time_format(val) {
      return dayjs(val).format('YYYY-MM-DD')
    }
  }
}
</script>

<style lang="less" scoped>
.search-box {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}
.add-btn {
  margin-top: 3px;
}
/deep/ .ql-editor {
  height: 250px;
}
.cover-img {
  height: 280px;
  width: 400px;
  object-fit: cover;
}
.el-pagination {
  margin-top: 10px;
}
</style>
